package com.client.messages;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import javax.annotation.Resource;
import javax.jms.*;

public class MessageDispatcher {
	
	private static Connection connection;
	
	@Resource(mappedName="jms/ConnectionFactory")
	 private static ConnectionFactory connectionFactory;
	
	@Resource(mappedName="jms/Topic")
	 private static Topic topic;
	 static Session mySess = null;
	
	public static void main(String[] args) {
		
		
		try{
		connectionFactory  = new com.sun.messaging.ConnectionFactory();
		connection = connectionFactory.createConnection();
		mySess = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		topic = new com.sun.messaging.Topic("moving");
		
		final MessageProducer myMsgProducer = mySess.createProducer(topic);
		final MessageConsumer myMsgConsumer = mySess.createConsumer(topic);
		
		final TextMessage myTextMsg = mySess.createTextMessage();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String stopchat="";
				try{
			       while(!stopchat.equals("quet")){
			        	Message msg = myMsgConsumer.receive();
						
						if(msg!= null){
					        if (msg instanceof TextMessage) {
					            TextMessage txtMsg = (TextMessage) msg;
					            stopchat = txtMsg.getText();
					            System.out.println("Read Message: " + stopchat);
					        }
						}
					}
				}catch(JMSException jms){
					System.out.println("Consumer receiver \n");
				}
				
			}
		}, "receive thread").start();
		
		
		new Thread(new Runnable() {

			 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			 
			 String stopchat="";
		 
			@Override
			public void run() {
				 while(!stopchat.equals("quet")){
					 try{
						 stopchat = in.readLine();
						 myTextMsg.setText(stopchat);
						 System.out.println("Sending message: "+ myTextMsg.getText());
						 myMsgProducer.send(myTextMsg);
					 }catch(IOException e){
						 System.err.println("I/O exception: "+ e.toString());
					 } catch (JMSException e) {
						 System.err.println("Consumer sender \n");
					}
				 }			
			}
		}, "sender thread").start(); 
        
        connection.start();
		
		} catch (Exception jmse) {
            System.out.println("Exception occurred : " + jmse.toString());
            jmse.printStackTrace();
        }finally{
        	
        }
	}
	
	@Override
	protected void finalize() throws Throwable {
		try {
    		if(connection != null)
    				connection.close();
    		if(mySess != null)
    				mySess.close();
    		System.err.println("close all");
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
}
